package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/swsk33/landsat-fetch/global"
	"gitee.com/swsk33/landsat-fetch/model"
	"gitee.com/swsk33/sclog"
)

// Login 登录
// 登录完成后会设定全局请求头X-Auth-Token
//
// username 用户名
//
// token 申请的M2M API Token
func Login(username, token string) error {
	bodyString := fmt.Sprintf("{\"username\":\"%s\",\"token\":\"%s\"}", username, token)
	response, e := global.SendRequest("/login-token", "POST", []byte(bodyString))
	if e != nil {
		sclog.ErrorLine("发送登录请求失败！")
		return e
	}
	// 反序列化
	var result model.BasicResponse[string]
	e = json.Unmarshal(response, &result)
	if e != nil {
		return e
	}
	// 检查是否失败
	if result.ErrorCode != nil {
		sclog.Error("登录失败！%s\n", result.ErrorMessage)
		return errors.New(fmt.Sprintf("%s", result.ErrorMessage))
	}
	// 设定全局Session
	global.AuthHeader = result.Data
	sclog.InfoLine("登录成功！")
	return nil
}